package cn.com.company.main.server;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

import cn.com.company.main.client.entity.FileModel;
import cn.com.company.main.client.entity.IcbomchildItem;
import cn.com.company.main.client.entity.TIcItem;
import cn.com.company.main.client.entity.TItem;
import cn.com.company.main.client.entity.VwWebbomIcitem;
import cn.com.company.main.client.entity.VwWebbomIcitemSimp;
import cn.com.company.main.client.entity.WebbomUserinfo;
import cn.com.company.main.client.service.GreetingService;
import cn.com.company.main.dao.BaseHibernateDAO;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public String greetServer(String input) throws IllegalArgumentException {
		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");

		input = escapeHtml(input);
		userAgent = escapeHtml(userAgent);

		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html
	 *            the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}

	@Override
	public WebbomUserinfo checkLoginUser(String loginname, String pwd) {
		String sql = "select * from webbom_userinfo where loginname='"
				+ loginname + "' and password='" + pwd + "'";
		BaseHibernateDAO dao = new BaseHibernateDAO();
		Session session = dao.getSession();
		SQLQuery query = session.createSQLQuery(sql);
		query.addEntity(WebbomUserinfo.class);
		@SuppressWarnings("unchecked")
		List<WebbomUserinfo> list = query.list();
		if (list == null || list.size() == 0) {
			return null;
		} else {
			return list.get(0);
		}
	}

	@Override
	public List<FileModel> getIcbomModel(FileModel model) {
		List<FileModel> modelList = new ArrayList<FileModel>();
		BaseHibernateDAO dao = new BaseHibernateDAO();
		Session session = dao.getSession();
		SQLQuery query = null;
		String sql = "";
		if (model == null) {
			FileModel fileModel = new FileModel("0", "物料", "root", null);
			modelList.add(fileModel);
		} else if ("root".equalsIgnoreCase(model.get("type") + "")) {
			sql = "select fitemid,fnumber,fname from t_item where fparentid=0 and fitemclassid=4 order by fnumber";
			query = session.createSQLQuery(sql);
			query.addEntity(TItem.class);
			@SuppressWarnings("unchecked")
			List<TItem> list = query.list();
			for (TItem entity : list) {
				String id = entity.getFnumber() + "";
				String itemid = entity.getFitemId() + "";
				String name = id + "（" + entity.getFname() + "）";
				String type = "father";
				FileModel fileModel = new FileModel(id, name, type, itemid);
				modelList.add(fileModel);
			}
		} else if ("father".equalsIgnoreCase(model.get("type") + "")) {
			sql = "select fitemid,fnumber,fname from t_item where fparentid='"
					+ model.getItemId() + "'";
			query = session.createSQLQuery(sql);
			query.addEntity(TItem.class);
			@SuppressWarnings("unchecked")
			List<TItem> list = query.list();
			for (TItem entity : list) {
				String id = entity.getFnumber() + "";
				String itemid = entity.getFitemId() + "";
				String name = id + "（" + entity.getFname() + "）";
				String type = "father";
				FileModel fileModel = new FileModel(id, name, type, itemid);
				modelList.add(fileModel);
			}
		}
		return modelList;
	}

	public List<VwWebbomIcitem> getIcItemByItemId(String itemId) {
		BaseHibernateDAO dao = new BaseHibernateDAO();
		Session session = dao.getSession();
		String sql = "select * from _vw_webbom_icitem where 1=1 ";
		if(itemId != null && !"".equals(itemId) && !"null".equalsIgnoreCase(itemId)){
			sql += " and fitemid=" + "'" + itemId + "'";
		}
		SQLQuery query = session.createSQLQuery(sql);
		query.addEntity(VwWebbomIcitem.class);
		@SuppressWarnings("unchecked")
		List<VwWebbomIcitem> list = query.list();
		return list;
	}
	
	public List<VwWebbomIcitemSimp> getIcItemList() {
		BaseHibernateDAO dao = new BaseHibernateDAO();
		Session session = dao.getSession();
		String sql = "select finterid,fitemid,fbomnumber,fnumber,fname,fversion,fuseStatus,fstatus,fenterTime from _vw_webbom_icitem order by fbomnumber";
		SQLQuery query = session.createSQLQuery(sql);
		query.addEntity(VwWebbomIcitemSimp.class);
		@SuppressWarnings("unchecked")
		List<VwWebbomIcitemSimp> list = query.list();
		return list;
	}

	public String updateUserPassword(String userId, String oldPwd, String newPwd) {
		BaseHibernateDAO dao = new BaseHibernateDAO();
		Session session = dao.getSession();
		String sql = "select password from webbom_userinfo where id=:userId";
		Query query = session.createSQLQuery(sql);
		query.setString("userId", userId);
		String password = (String) query.uniqueResult();
		if (!oldPwd.equals(password)) {
			return "error";
		} else {
			sql = "update webbom_userinfo set password=:password where id =:userId";
			query = session.createSQLQuery(sql);
			query.setString("password", newPwd);
			query.setString("userId", userId);
			query.executeUpdate();
			return "success";
		}
	}

	@Override
	public List<IcbomchildItem> getIcbomItem(IcbomchildItem model,
			String interId) {
		BaseHibernateDAO dao = new BaseHibernateDAO();
		Session session = dao.getSession();
		SQLQuery query = null;
		String sql = "select * from _vw_webbom_childitem where 1=1 ";
		if (model == null) {
			sql += "and finterid='" + interId + "'";
		} else {
			String fnumber = model.getFnumber();
			if (fnumber.startsWith("60") || fnumber.startsWith("70")
					|| fnumber.startsWith("75") || fnumber.startsWith("78")
					|| fnumber.startsWith("89")) {
				sql += "and finterid=(select finterid from icbom where FStatus='1' and FUseStatus='1072' and fitemid='"
						+ model.getFitemId() + "')";
			} else {
				sql += "and fparentid='" + model.getFitemId() + "'";
			}
		}
		query = session.createSQLQuery(sql);
		query.addEntity(IcbomchildItem.class);
		@SuppressWarnings("unchecked")
		List<IcbomchildItem> list = query.list();
		return list;
	}

	public List<TItem> getItemByConditon(TItem item) {
		BaseHibernateDAO dao = new BaseHibernateDAO();
		Session session = dao.getSession();
		String sql = "select top 20 * from t_item where 1=1 ";
		if (item != null) {
			String fnumber = item.getFnumber();
			String fname = item.getFname();
			if (fnumber != null) {
				sql += " and fnumber like '%" + fnumber + "%' ";
			}
			if (fname != null) {
				sql += " and fname like '%" + fname + "%' ";
			}
		}
		SQLQuery query = session.createSQLQuery(sql);
		query.addEntity(TItem.class);
		@SuppressWarnings("unchecked")
		List<TItem> list = query.list();
		return list;
	}

	public List<TIcItem> getTIcItemByItemId(String itemId) {
		BaseHibernateDAO dao = new BaseHibernateDAO();
		Session session = dao.getSession();
		String sql = "select b.fitemid,b.fparentid,b.fnumber,b.fname,b.fmodel,k.fname as ferpclsid "
				+ " from t_icitem b inner join t_SubMessage k ON b.FErpClsID = k.FInterID where b.fitemid="
				+ "'" + itemId + "'";
		SQLQuery query = session.createSQLQuery(sql);
		query.addEntity(TIcItem.class);
		@SuppressWarnings("unchecked")
		List<TIcItem> list = query.list();
		return list;
	}

	public List<TIcItem> getIcbomParent(TIcItem model, String itemId) {
		BaseHibernateDAO dao = new BaseHibernateDAO();
		Session session = dao.getSession();
		SQLQuery query = null;
		String sql = "";

		if(model == null){
			//do nothing
		}else{
			itemId = model.getFitemId() + "";
		}
		sql = "select b.fitemid,b.fparentid,b.fnumber,b.fname,b.fmodel,k.FName as ferpclsid "
				+ "from t_icitem b inner join t_SubMessage k ON b.FErpClsID = k.FInterID "
				+ "where fitemid in (select fitemid from icbom  where finterid in "
				+ "(select finterid from icbomchild where fitemid='"
				+ itemId + "') and fusestatus='1072')";
	
		query = session.createSQLQuery(sql);
		query.addEntity(TIcItem.class);
		@SuppressWarnings("unchecked")
		List<TIcItem> result = query.list();
		return result;
	}
}
